package codeOfChapter04;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import homework04.Column2;
import homework04.ID2;

public class ColumnInfo {
	private String columnName;
	private Class<?> type;
	private boolean isID = false;
	private boolean nullable = true;
	private int length = 32;
	private boolean needPersist = false;

	public ColumnInfo parse(Field field) {
		this.setColumnName(field.getName());
		this.type = field.getType();
		Annotation[] annotations = field.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation.annotationType().equals(Column2.class)) {
				this.needPersist = true;
				Column2 column = (Column2) annotation;
				if (!column.value().equals("")) {
					this.setColumnName(column.value());
				}
				this.nullable = column.nullable();
				if (column.length() != -1) {
					this.length = column.length();
				}
			} else if (annotation.annotationType().equals(ID2.class)) {
				this.needPersist = true;
				ID2 id = (ID2) annotation;
				this.isID = true;
				if (!id.value().equals("")) {
					this.setColumnName(id.value());
				}
			}
		}

		if (this.needPersist) {
			return this;
		} else {
			return null;
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (this.type.equals(String.class)) {
			sb.append(" " + "VARCHAR(" + this.length + ")");
		} else if (this.type.equals(Integer.class)) {
			sb.append(" " + "INT");
		}
		if (isID) {
			sb.append(" " + "PRIMARY　KEY");
		}
		if (!this.isNullable()) {
			sb.append(" " + "NOT NULL");
		}
		sb.append(";");
		return sb.toString();

	}

	public Class<?> getType() {
		return type;
	}

	public void setType(Class<?> type) {
		this.type = type;
	}

	public boolean isID() {
		return isID;
	}

	public void setID(boolean isID) {
		this.isID = isID;
	}

	public boolean isNullable() {
		return nullable;
	}

	public void setNullable(boolean nullable) {
		this.nullable = nullable;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public boolean isNeedPersist() {
		return needPersist;
	}

	public void setNeedPersist(boolean needPersist) {
		this.needPersist = needPersist;
	}

	public String getColumnName() {
		return columnName;
	}

	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}
}
